/**
 ******************************************************************************
 * @file    
 * @author 
 * @Version 
 * @Date    
 * @brief 
 *******************************************************************************  
 **/
#include "zb32l03x_hal.h"
#include "bsp_flash.h"

/*
*********************************************************************************************************
*	功能说明: 初始化
*	形    参:
*	返 回 值:
* 说    明：
*********************************************************************************************************
*/

void bsp_flash_init(void)
{
    
}
/*
*********************************************************************************************************
*	功能说明: 片选
*	形    参:
*	返 回 值:
* 说    明：
*********************************************************************************************************
*/
void bsp_flash_erase(void)
{
    FLASH_EraseInitTypeDef flasheraseinit = {0};
    uint32_t errpage;
    /**
     * Flash page erase from
     * FLASH_PROGRAM_ADDRESS_START ~ FLASH_PROGRAM_ADDRESS_END
     */
    flasheraseinit.TypeErase = FLASH_TYPEERASE_PAGES;
    flasheraseinit.PageAddress = FLASH_PROGRAM_ADDRESS_START;
    flasheraseinit.NbPages = (FLASH_PROGRAM_ADDRESS_END - FLASH_PROGRAM_ADDRESS_START) / FLASH_PAGE_SIZE;
    if (HAL_FLASH_Erase(&flasheraseinit, &errpage) != HAL_OK)
    {
    }
}

/*
*********************************************************************************************************
*	功能说明: 片选
*	形    参:
*	返 回 值:
* 说    明：
*********************************************************************************************************
*/
int bsp_flash_prog(uint8_t *buff, uint32_t len)
{
    /**
     *  TypeProgram:
     *      FLASH_TYPEPROGRAM_BYTE
     *      FLASH_TYPEPROGRAM_HALFWORD
     *      FLASH_TYPEPROGRAM_WORD
     */
    int err_code = 0;
    uint32_t offset = 0;
    uint64_t value = 0;
    uint32_t TypeProgram = FLASH_TYPEPROGRAM_BYTE;
    uint32_t startadd;
    uint32_t i = 0;

    offset = 1;
    value = FLASH_PROGRAM_DATA_BYTE;

    if (len > (FLASH_PROGRAM_ADDRESS_END - FLASH_PROGRAM_ADDRESS_START))
    {
        return -1;
    }

    /**
     *  Flash program
     *       from FLASH_PROGRAM_ADDRESS_START to FLASH_PROGRAM_ADDRESS_END
     */
    startadd = FLASH_PROGRAM_ADDRESS_START;
    while (startadd < FLASH_PROGRAM_ADDRESS_END)
    {
        if (HAL_FLASH_Program(TypeProgram, startadd, buff[i++]) == HAL_OK)
        {
            startadd += offset;
        }
        else
        {
            return -3;
        }
    }

    return 0;
}

int bsp_flash_read( uint8_t *buff, uint32_t len)
{
    uint32_t i;
    uint32_t startadd=FLASH_PROGRAM_ADDRESS_START;
    if (len > (FLASH_PROGRAM_ADDRESS_END - FLASH_PROGRAM_ADDRESS_START))
    {
        return -1;
    }
    for (i = 0; i < len; i++)
    {
        buff[i] = *(uint8_t *)(startadd + i);
    }
}
